<template>
  <div class="xts-reports">
    <h1>XTS运行报告</h1>
    
    <div class="search-bar">
      <el-input v-model="searchOwner" placeholder="组织名称" clearable />
      <el-input v-model="searchName" placeholder="库名称" clearable />
      <el-button type="primary" @click="searchXTSReports">
        <el-icon><Search /></el-icon>
      </el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="showAddDialog">添加XTS报告</el-button>
    </div>
    
    <el-table :data="xtsReports" style="width: 100%" v-loading="loading">
      <el-table-column prop="displayId" label="序号" width="80" />
      <el-table-column prop="owner" label="组织名称" width="120" />
      <el-table-column prop="name" label="库名称" width="120" />
      <el-table-column prop="iterationVersion" label="迭代版本" width="120" />
      <el-table-column prop="apiVersion" label="API版本" width="120" />
      <el-table-column prop="runningResult" label="运行结果" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.runningResult === 'pass' ? 'success' : 'danger'">
            {{ scope.row.runningResult === 'pass' ? '通过' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="failReason" label="失败原因" />
      <el-table-column prop="reportAddress" label="报告地址" width="150" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteXTSReport(scope.row.id)">删除</el-button>
          <el-button size="small" type="success" @click="runXTS(scope.row)" :disabled="isRunning">
            {{ isRunning ? '运行中' : '运行' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑XTS报告对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑XTS报告' : '添加XTS报告'">
      <el-form :model="form" label-width="120px">
        <el-form-item label="组织名称">
          <el-input v-model="form.owner" />
        </el-form-item>
        <el-form-item label="库名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="迭代版本">
          <el-input v-model="form.iterationVersion" />
        </el-form-item>
        <el-form-item label="API版本">
          <el-input v-model="form.apiVersion" />
        </el-form-item>
        <el-form-item label="运行结果">
          <el-select v-model="form.runningResult" placeholder="请选择运行结果">
            <el-option label="通过" value="pass" />
            <el-option label="失败" value="fail" />
          </el-select>
        </el-form-item>
        <el-form-item label="失败原因">
          <el-input v-model="form.failReason" type="textarea" :disabled="form.runningResult === 'pass'" />
        </el-form-item>
        <el-form-item label="报告地址">
          <el-input v-model="form.reportAddress" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveXTSReport">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { xtsReportApi } from '../api'
import { connectWebSocket, disconnectWebSocket, subscribeToTopic, unsubscribeFromTopic, sendMessage } from '../utils/websocket'

export default {
  name: 'XTSReports',
  components: {
    Search
  },
  setup() {
    const xtsReports = ref([])
    const loading = ref(false)
    const searchOwner = ref('')
    const searchName = ref('')
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const isRunning = ref(false)
    const form = ref({
      id: null,
      owner: '',
      name: '',
      iterationVersion: '',
      apiVersion: '',
      runningResult: 'fail',
      failReason: '',
      reportAddress: ''
    })

    const loadXTSReports = async () => {
      loading.value = true
      try {
        const response = await xtsReportApi.getAll()
        xtsReports.value = response.data
      } catch (error) {
        console.error('加载XTS报告失败:', error)
        ElMessage.error('加载XTS报告失败')
      } finally {
        loading.value = false
      }
    }

    const searchXTSReports = async () => {
      if (!searchOwner.value && !searchName.value) {
        loadXTSReports()
        return
      }
      
      loading.value = true
      try {
        const response = await xtsReportApi.getByOwnerAndName(searchOwner.value, searchName.value)
        xtsReports.value = response.data
      } catch (error) {
        console.error('搜索XTS报告失败:', error)
        ElMessage.error('搜索XTS报告失败')
      } finally {
        loading.value = false
      }
    }

    const resetSearch = () => {
      searchOwner.value = ''
      searchName.value = ''
      loadXTSReports()
    }

    const showAddDialog = () => {
      isEdit.value = false
      form.value = {
        id: null,
        owner: '',
        name: '',
        iterationVersion: '',
        apiVersion: '',
        runningResult: 'fail',
        failReason: '',
        reportAddress: ''
      }
      dialogVisible.value = true
    }

    const showEditDialog = (xtsReport) => {
      isEdit.value = true
      form.value = { ...xtsReport }
      dialogVisible.value = true
    }

    const saveXTSReport = async () => {
      try {
        if (isEdit.value) {
          await xtsReportApi.update(form.value.id, form.value)
          ElMessage.success('XTS报告更新成功')
        } else {
          await xtsReportApi.create(form.value)
          ElMessage.success('XTS报告添加成功')
        }
        dialogVisible.value = false
        loadXTSReports()
      } catch (error) {
        console.error('保存XTS报告失败:', error)
        ElMessage.error('保存XTS报告失败')
      }
    }

    const deleteXTSReport = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条XTS报告吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await xtsReportApi.delete(id)
        ElMessage.success('XTS报告删除成功')
        loadXTSReports()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除XTS报告失败:', error)
          ElMessage.error('删除XTS报告失败')
        }
      }
    }

    const runXTS = (xtsReport) => {
      isRunning.value = true
      ElMessage.info('XTS测试开始运行...')
      
      // 模拟XTS运行过程，实际项目中应该通过WebSocket接收后端的实时状态
      setTimeout(() => {
        // 模拟运行完成
        sendMessage('/app/xts/status', {
          ...xtsReport,
          runningResult: Math.random() > 0.3 ? 'pass' : 'fail',
          failReason: Math.random() > 0.3 ? '' : '测试用例执行失败',
        })
        
        isRunning.value = false
        ElMessage.success('XTS测试运行完成')
        loadXTSReports()
      }, 3000)
    }

    // WebSocket相关
    const setupWebSocket = () => {
      connectWebSocket(() => {
        subscribeToTopic('/topic/xts/status', (data) => {
          // 更新XTS状态
          const index = xtsReports.value.findIndex(item => item.id === data.id)
          if (index !== -1) {
            xtsReports.value[index] = data
          }
        })
      })
    }

    onMounted(() => {
      loadXTSReports()
      setupWebSocket()
    })

    onUnmounted(() => {
      unsubscribeFromTopic('/topic/xts/status')
      disconnectWebSocket()
    })

    return {
      xtsReports,
      loading,
      searchOwner,
      searchName,
      dialogVisible,
      isEdit,
      isRunning,
      form,
      loadXTSReports,
      searchXTSReports,
      resetSearch,
      showAddDialog,
      showEditDialog,
      saveXTSReport,
      deleteXTSReport,
      runXTS
    }
  }
}
</script>

<style scoped>
.xts-reports {
  padding: 20px;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  max-width: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>